const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let account 	= req.body.account;
	let password 	= req.body.password;

	// 如果没有传账户和密码过来的话
	if (account == undefined || password == undefined) {
		sendResponse('error', '参数缺失', null, res);
		return;
	}

	// 获取数据库连接
	pool.getConnection(function(err, connection) {
		if (err) {
			sendResponse('error','数据库内部错误', null, res);
			return;
		}

		let params = [account, password];
		// 执行语句
		connection.query('SELECT id, account, name FROM admin WHERE account = ? and password = ? and able = 1', params, function (error, rows, fields) {
			// 释放连接
			connection.release();

			if (error) { 
				sendResponse('error','数据库内部错误', null, res);
				return;
			}

			// 如果根据该账号密码匹配到一行，即匹配正确
			if (rows.length == 1) {
				req.session.adminIsLogin 		= true;
				req.session.adminAccount 	= rows[0].account;
				req.session.adminName 		= rows[0].name;
				req.session.adminId			= rows[0].id;
				let result = {
					account: rows[0].account,
					name: rows[0].name,
					id: rows[0].id
				}
				sendResponse('ok','登录成功', null, res);
			} else {
				sendResponse('error','账号或密码错误', null, res);
			}

		})	

	});

}